﻿using AutoMapper;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet
{
    public class PalletService : IPalletService
    {
        private readonly SimpleRepositroy<TPallets> palletrepost;

        public PalletService(SimpleRepositroy<TPallets> palletrepost)
        {
            this.palletrepost = palletrepost;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddPallet(PalletDto dto)
        {
            try
            {
                TPallets pallet = new TPallets();
                pallet.PalletBarcode = dto.PalletBarcode;
                pallet.PalletName = dto.PalletName;
                pallet.LocationCode = dto.LocationCode;
                pallet.Status = dto.Status;
                pallet.CreateDate = dto.CreateDate;
                pallet.ModifyDate = DateTime.Now;
                pallet.DisplayOrder = dto.DisplayOrder;
                pallet.Opprint = dto.Opprint;
                pallet.PrintTimes = dto.PrintTimes;
                pallet.LocationName = dto.LocationName;
                pallet.ErplocationName = dto.ErplocationName;
                pallet.Type = dto.Type;
                pallet.WarehouseId = dto.WarehouseId;
                pallet.WarehouseCode = dto.WarehouseCode;
                pallet.WarehouseName = dto.WarehouseName;
                pallet.CreateDate = DateTime.Now;
                pallet.ModifyDate = DateTime.Now;

                if (!palletrepost.Insert(pallet))
                {
                    return false;
                }
                return true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdatePallet(PalletDto dto)
        {
            try
            {
                TPallets pallet = new TPallets()
                {
                    Id = dto.Id,
                    PalletBarcode = dto.PalletBarcode,
                    PalletName = dto.PalletName,
                    LocationCode = dto.LocationCode,
                    Status = dto.Status,
                    CreateDate = dto.CreateDate,
                    ModifyDate = DateTime.Now,
                    DisplayOrder = dto.DisplayOrder,
                    Opprint = dto.Opprint,
                    PrintTimes = dto.PrintTimes,
                    LocationName = dto.LocationName,
                    ErplocationName = dto.ErplocationName,
                    Type = dto.Type,
                    WarehouseId = dto.WarehouseId,
                    WarehouseCode = dto.WarehouseCode,
                    WarehouseName = dto.WarehouseName
                };
                if (!palletrepost.Update(pallet))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 托盘分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TPallets> GetPallets(string name, int type, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = palletrepost.GetList();
                if (!string.IsNullOrEmpty(name))
                {
                    list = list.Where(x => x.PalletName.Contains(name)).ToList();
                }
                if (type != -1)
                {
                    list = list.Where(x => x.Type == type).ToList();
                }
                totalCount = list.Count();
                list = list.OrderBy(x => x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TPallets GetPallet(int id)
        {
            return palletrepost.GetFirst(p=>p.Id == id);
        }

        public bool BatchAddPallet(List<TPallets> pallets)
        {
            if (pallets.Count > 0)
            {
                try
                {
                    palletrepost.AsTenant().BeginTran();
                    foreach (var item in pallets)
                    {
                        if (!palletrepost.Insert(item))
                        {
                            palletrepost.AsTenant().RollbackTran();
                            return false;
                        }
                    }

                    //提交事务
                    palletrepost.AsTenant().CommitTran();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    palletrepost.AsTenant().RollbackTran();
                    throw;
                }
            }
            return false;
        }

        /// <summary>
        /// 批量添加托盘
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPalletList(BatchPalletDTO m, out string errMsg)
        {
            errMsg = string.Empty;
            string name = "";
            string code = "";
            string LogicalPartCode = "";
            if (m.Type == 0)
            {
                code = "A";
                name = "托盘-";
                LogicalPartCode = "PalletArea";
            }
            else if (m.Type == 1)
            {
                code = "B";
                name = "大料箱-";
                LogicalPartCode = "BulkyArea";
            }
            else if (m.Type == 2)
            {
                code = "C";
                name = "小料箱-";
                LogicalPartCode = "SmallArea";
            }
            else if (m.Type == 3)
            {
                code = "Y1";
                name = "易燃库1-";
                LogicalPartCode = "FlammableWarehouse1";
            }
            else if (m.Type == 4)
            {
                code = "Y2";
                name = "易燃库2-";
                LogicalPartCode = "FlammableWarehouse2";
            }
            else if (m.Type == 5)
            {
                code = "Y3";
                name = "易燃库3-";
                LogicalPartCode = "FlammableWarehouse3";

            }
            else if (m.Type == 6)
            {
                code = "Y4";
                name = "易燃库4-";
                LogicalPartCode = "FlammableWarehouse4";
            }
            try
            {
                palletrepost.AsTenant().BeginTran();
                int pallnum;
                var pallList = palletrepost.GetList(p => p.Type == m.Type);
                if (pallList is null || pallList.Count() <= 0)
                {
                    pallnum = 1001;
                }
                else
                {
                    var pall = pallList.OrderByDescending(p => p.DisplayOrder).FirstOrDefault();
                    pallnum = Convert.ToInt32(pall.PalletBarcode.Substring(1)) + 1;
                }
                for (int i = 0; i < m.Num; i++)
                {

                    TPallets pallet = new TPallets()
                    {
                        PalletBarcode = code + pallnum,
                        PalletName = name + pallnum,
                        DisplayOrder = pallnum,
                        Status = 1,
                        LocationCode = "",
                        LocationName = "",
                        Type = m.Type,
                        CreateDate = DateTime.Now
                    };

                    if (!palletrepost.Insert(pallet))
                    {
                        errMsg = "批量添加托盘失败，终止添加的托盘为：" + pallet.PalletBarcode;
                        palletrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    pallnum++;
                }
                errMsg = "添加成功";
                palletrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                palletrepost.AsTenant().RollbackTran();
                return false;
                throw;
            }
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelPallet(int ids)
        {
            try
            {
                var pall = palletrepost.GetFirst(p=>p.Id == ids);
                if (pall == null)
                {
                    return false;
                }
                if (!palletrepost.Delete(pall))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 托盘打印
        /// </summary>
        /// <param name="codes"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool PallPrintCount(string[] codes, out string errMsg)
        {
            errMsg = string.Empty;
            if (codes.Count() <= 0)
            {
                errMsg = "Id有误";
                return false;
            }
            try
            {
                palletrepost.AsTenant().BeginTran();
                foreach (string code in codes)
                {
                    var pall = palletrepost.GetFirst(p => p.PalletBarcode == code);
                    if (pall == null)
                    {
                        palletrepost.AsTenant().RollbackTran();
                        errMsg = "未查询出托盘";
                        return false;
                    }
                    pall.PrintTimes = pall.PrintTimes + 1;
                    if (!palletrepost.Update(pall))
                    {
                        palletrepost.AsTenant().RollbackTran();
                        errMsg = "修改箱号或托盘打印次数失败！";
                        return false;
                    }
                }
                palletrepost.AsTenant().CommitTran();
                errMsg = "修改打印次数成功";
                return true;
            }
            catch (Exception ex)
            {
                palletrepost.AsTenant().RollbackTran();
                errMsg = ex.Message;
                return false;
                throw;
            }

        }
    }
}